What I am trying to do is implement a simple inline editing, I'm using a normal div to display the text when the edit state is false, and render an input when the edit state is true.
The problem I'm facing is that the input doesn't wrap around the text content it's got, like a div with display: inline-block would. I tried setting the size attribute of the input to be that of the current value's length, but it's not wrapping around the content perfectly.
Any ideas how to do it? I guess contentEditable on the span itself, without an input, is an option, but I want to be able to select all the content in the input when it gets the focus.
Here is the code.
import { useState, useRef, useEffect } from "react";
export default function App() {
const [value, setValue] = useState("test");
const [active, setActive] = useState(false);
const ref = useRef();
useEffect(() => {
ref.current?.select();
}, [active]);
const length = value.split(" ").join("").length;
return (
<>
{!active && <span onClick={() => setActive(true)}>{value}</span>}
{active && (
<input
value={value}
size={length}
ref={ref}
onChange={(e) => setValue(e.target.value)}
onBlur={() => setActive(false)}
/>
)}
</>
);
}